package com.hxl.tech.gateway.core.filter;


import com.hxl.tech.gateway.core.util.CacheManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.setResponseStatus;

@Slf4j
@Component
@RequiredArgsConstructor
public class LimitIpFilter implements GlobalFilter, Ordered {

    private final CacheManager cacheManager;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        return Mono.subscriberContext().flatMap(ctx -> {
            String ip = exchange.getRequest().getHeaders().getFirst("X-FORWARDED-FOR");
            if (Objects.isNull(ip)) {
                ip = Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress();
            }

            if(cacheManager.checkIpLimit(ip)) {
                setResponseStatus(exchange, HttpStatus.FORBIDDEN);
                log.info("网关限制ip:[{}]禁止调用接口", ip);
                return exchange.getResponse().setComplete();
            }

            return chain.filter(exchange);
        });
    }

    @Override
    public int getOrder() {
        return 5001;
    }
}
